package com.rr.mymoney.dao.impl.hibernate;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.rr.mymoney.dao.CategoryDao;
import com.rr.mymoney.model.Category;

@Transactional
@Repository
public class CategoryDaoImpl extends AbstractDao implements CategoryDao {

    private static transient Logger log = Logger.getLogger(CategoryDaoImpl.class);

    public void saveOrUpdate(Category category) {

	getCurrentSession().saveOrUpdate(category);
	getCurrentSession().flush();
    }

    public Category get(Long id) {
	return (Category) getCurrentSession().get(Category.class, id);
    }

    public void delete(Category category) {
	getCurrentSession().delete(category);
    }

    @SuppressWarnings("unchecked")
    public List<Category> getByUserId(List<Long> userIds, boolean onlyRoots) {
	String onlyRootsCondition = "";
	if (onlyRoots) {
	    onlyRootsCondition = " and c.parentCategory is null";
	}
	List<Category> rtn = null;
	if (userIds != null && userIds.size() > 0) {
	    rtn = findByNamedParam("from Category c where c.user.id in (:userIds) " + onlyRootsCondition, new String[] { "userIds" },
		    new Object[] { userIds });
	} else {
	    rtn = find("from Category c where c.user.id is null " + onlyRootsCondition);
	}
	return rtn;
    }

    @SuppressWarnings("unchecked")
    public List<Category> getByUserIdAndName(List<Long> userIds, String name) {
	if (userIds != null && userIds.size() > 0) {
	    return findByNamedParam("from Category c where c.user.id in (:userIds) and name = :name", new String[] { "userIds", "name" },
		    new Object[] { userIds, name });

	} else {
	    return find("from Category c where c.user.id is null and name = ?", name);
	}
    }

    @Override
    public void check(Category category) {
	log.debug(getCurrentSession().contains(category) + " " + category);
    }
}
